package com.sinosoft.taxbenefit.manage.bargainquery.biz.service.impl;

import java.net.URL;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.sinosoft.platform.base.TaxBaseService;
import com.sinosoft.platform.common.config.SystemConstants;
import com.sinosoft.platform.common.util.DateUtil;
import com.sinosoft.platform.common.util.StringUtil;
import com.sinosoft.taxbenefit.api.config.ENUM_BZ_RESPONSE_RESULT;
import com.sinosoft.taxbenefit.api.config.ENUM_SENDSERVICE_CODE;
import com.sinosoft.taxbenefit.api.dto.request.TaxFaulTaskDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.ParamHeadDTO;
import com.sinosoft.taxbenefit.core.common.biz.service.CommonCodeService;
import com.sinosoft.taxbenefit.core.common.config.ENUM_EBAO_SERVICE_PORT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RC_STATE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RESULT_CODE;
import com.sinosoft.taxbenefit.core.common.dto.EbaoServerPortDTO;
import com.sinosoft.taxbenefit.core.common.dto.SendLogDTO;
import com.sinosoft.taxbenefit.core.common.dto.ThirdSendDTO;
import com.sinosoft.taxbenefit.core.ebaowebservice.BusinessCheckService;
import com.sinosoft.taxbenefit.core.ebaowebservice.BusinesssCheckService;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseBody;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseHeader;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseJSON;
import com.sinosoft.taxbenefit.core.faultTask.biz.service.FaultTaskService;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxBusinessCollateDetailMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxRequestBusinessCollateMapper;
import com.sinosoft.taxbenefit.core.generated.model.TaxBusinessCollateDetail;
import com.sinosoft.taxbenefit.core.generated.model.TaxRequestBusinessCollate;
import com.sinosoft.taxbenefit.core.generated.model.TaxRequestBusinessCollateExample;
import com.sinosoft.taxbenefit.core.generated.model.TaxRequestBusinessDetail;
import com.sinosoft.taxbenefit.manage.bargainquery.biz.service.BargainQueryService;
import com.sinosoft.taxbenefit.manage.bargainquery.dto.BargainQueryDTO;
import com.sinosoft.taxbenefit.manage.bargainquery.dto.BusinessCollateDetailDTO;
import com.sinosoft.taxbenefit.manage.bargainquery.dto.BusinessDetailDTO;
import com.sinosoft.taxbenefit.manage.bargainquery.dto.ReqBargainQueryDTO;
import com.sinosoft.taxbenefit.manage.bargainquery.dto.RequestBusinessCollateDTO;
import com.sinosoft.taxbenefit.manage.bargainquery.dto.ResBargainQueryDTO;
import com.sinosoft.taxbenefit.manage.bargainquery.dto.ResBargainQueryDetailDTO;
import com.sinosoft.taxbenefit.manage.bargainquery.mapper.BusinessCollateDetailMapper;
import com.sinosoft.taxbenefit.manage.bargainquery.mapper.BusinessCollateMapper;
import com.sinosoft.taxbenefit.manage.bargainquery.mapper.BusinessDetailMapper;
import com.sinosoft.taxbenefit.manage.base.page.Pager;

@Service
public class BargainQueryServiceImpl extends TaxBaseService implements BargainQueryService {
	@Autowired
	CommonCodeService commonCodeService;
	@Autowired
	TaxRequestBusinessCollateMapper taxRequestBusinessCollateMapper;
	@Autowired
	TaxBusinessCollateDetailMapper taxBusinessCollateDetailMapper;
	
	@Autowired
	FaultTaskService faultTaskService;
	@Autowired
	BusinessCollateMapper businessCollateMapper;
	@Autowired
	BusinessCollateDetailMapper businessCollateDetailMapper;
	@Autowired
	BusinessDetailMapper businessDetailMapper;
	
	//获得报文头
	ParamHeadDTO paramHead = this.initParamHeadDTO();
	@Override
	public void BargainQuery(ReqBargainQueryDTO reqBargainQueryDTO, Integer bid) {
		try {
			//查询日期当天交易记录
			TaxRequestBusinessCollate taxRequestBusinessCollate = taxRequestBusinessCollateMapper.selectByPrimaryKey(bid);
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.BARGAIN_CHECK_QUERY.code(), paramHead, reqBargainQueryDTO);
			logger.info("交易核对信息查询（请求中保信）JSON 数据内容：" + JSONObject.toJSONString(thirdSendDTO)); 
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.BARGAIN_CHECK_QUERY.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			BusinesssCheckService service = new BusinesssCheckService(wsdlLocation);
			BusinessCheckService servicePort = service.getBusinessCheckServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.businessCheck(thirdSendDTO.getHead(), thirdSendDTO.getBody(), responseHeaderHolder, responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("交易核对信息查询（中保信响应）JSON 数据内容："+responseBody.getJsonString());
			//封装中保信返回报文
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			//封装发送报文日志对象
			SendLogDTO sendLog = new SendLogDTO();
			sendLog.setSerialNo(paramHead.getSerialNo());
			sendLog.setPortCode(ENUM_EBAO_SERVICE_PORT_CODE.POLICY_IN_TRANSFER_UPLOAD.code());
			sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
			sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
			sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
			sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
			sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			commonCodeService.addLogSend(sendLog);
			if(ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())){
				if(!StringUtil.isEmpty(responseBody.getJsonString())){
					ResBargainQueryDTO resBargainQueryDTO = JSONObject.parseObject(responseBody.getJsonString(), ResBargainQueryDTO.class);
					if (resBargainQueryDTO.getTotal() != null) {
						taxRequestBusinessCollate.setCollateNum(resBargainQueryDTO.getTotal().getTotalNum().intValue());
						taxRequestBusinessCollate.setColSuccessNum(resBargainQueryDTO.getTotal().getSuccessNum().intValue());
						taxRequestBusinessCollate.setColFailNum(resBargainQueryDTO.getTotal().getFailNum().intValue());
						taxRequestBusinessCollate.setSuccessFlag(ENUM_RC_STATE.SUCCESS.getCode());
						taxRequestBusinessCollate.setUpdateId(SystemConstants.SYS_OPERATOR);
						taxRequestBusinessCollate.setUpdateTime(DateUtil.getCurrentDate());
						taxRequestBusinessCollateMapper.updateByPrimaryKeySelective(taxRequestBusinessCollate);
					}
					if (resBargainQueryDTO.getDetail() != null) {
						for (ResBargainQueryDetailDTO resBargainQueryDetailDTO : resBargainQueryDTO.getDetail()) {
							TaxBusinessCollateDetail taxBusinessCollateDetail = new TaxBusinessCollateDetail();
							taxBusinessCollateDetail.setBusId(taxRequestBusinessCollate.getSid());
							taxBusinessCollateDetail.setPolicyNo(resBargainQueryDetailDTO.getPolicyNo());
							taxBusinessCollateDetail.setSequenceNo(resBargainQueryDetailDTO.getSequenceNo());
							taxBusinessCollateDetail.setEdorNo(resBargainQueryDetailDTO.getEndorsementNo());
							taxBusinessCollateDetail.setClaimNo(resBargainQueryDetailDTO.getClaimNo());
							taxBusinessCollateDetail.setRenewFeeNo(resBargainQueryDetailDTO.getFeeId());
							taxBusinessCollateDetail.setFeeStatus(resBargainQueryDetailDTO.getFeeStatus());
							taxBusinessCollateDetail.setRenewEndorsementNo(resBargainQueryDetailDTO.getRenewalEndorsementNo());
							taxBusinessCollateDetail.setFeeId(resBargainQueryDetailDTO.getComFeeId());
							taxBusinessCollateDetail.setCreateId(SystemConstants.SYS_OPERATOR);
							taxBusinessCollateDetail.setCreateTime(DateUtil.getCurrentDate());
							taxBusinessCollateDetailMapper.insert(taxBusinessCollateDetail);
							logger.info("插入数据成功!");
						}
					}
				}
			} else {
				logger.info("交易核对信息查询中保信无返回数据! 错误信息为：" + responseHeader.getResultMessage());
				taxRequestBusinessCollate.setCollateNum(0);
				taxRequestBusinessCollate.setColSuccessNum(0);
				taxRequestBusinessCollate.setColFailNum(0);
				taxRequestBusinessCollate.setSuccessFlag(ENUM_RC_STATE.FAIL.getCode());
				taxRequestBusinessCollate.setUpdateId(SystemConstants.SYS_OPERATOR);
				taxRequestBusinessCollate.setUpdateTime(DateUtil.getCurrentDate());
				taxRequestBusinessCollateMapper.updateByPrimaryKeySelective(taxRequestBusinessCollate);
				logger.info("插入失败数据成功！");
			}
		} catch (Exception e) {
			logger.error("交易核对信息查询处理发生异常!"+e.getMessage());
			e.printStackTrace();
		}
		logger.info("交易核对信息查询处理结束");
	}
	/**
	 * 查询交易记录返回DTO
	 */
	@Override
	public RequestBusinessCollateDTO queryRequestBusinessCollateDTOByDay(String dataStr) {
		return businessCollateMapper.selectBusinessCollateByDate(dataStr);
	}
	/**
	 * 封装请求报文头
	 */
	@Override
	public ParamHeadDTO initParamHeadDTO() {
		ParamHeadDTO paramHead = new ParamHeadDTO();
		paramHead.setSerialNo(UUID.randomUUID().toString());
		paramHead.setAreaCode("440000");
		paramHead.setPortCode("CHK001");
		paramHead.setRecordNum("1");
		paramHead.setPortName("交易核对信息查询");
		return paramHead;
	}
	
	/**
	 * 查询指定日期的交易记录数
	 */
	@Override
	public List<TaxRequestBusinessCollate> queryByList(BargainQueryDTO page) {
		Integer rowCount =businessCollateMapper.queryByCount(page);
		Pager p = page.getPager();
		p.setRowCount(rowCount);
		p.setPageOffset(page.getPage() * page.getRows());
		p.setPageTail(page.getRows() * (page.getPage() - 1));
		return businessCollateMapper.queryByList(page);
	}
	
	/**
	 * 查询指定日期的交易详细记录
	 */
	@Override
	public List<TaxBusinessCollateDetail> queryByList(BusinessCollateDetailDTO page) {
		Integer rowCount =businessCollateDetailMapper.queryByCount(page);
		Pager p = page.getPager();
		p.setRowCount(rowCount);
		p.setPageOffset(page.getPage() * page.getRows());
		p.setPageTail(page.getRows() * (page.getPage() - 1));
		return businessCollateDetailMapper.queryByList(page);
	}
	@Override
	public TaxRequestBusinessCollate queryBySid(Integer sid) {	
		return taxRequestBusinessCollateMapper.selectByPrimaryKey(sid);
	}
	@Override
	public List<TaxRequestBusinessDetail> queryByBusinessDate(BusinessDetailDTO page) {
		Integer rowCount = businessDetailMapper.queryByCount(page.getBusinessDate());
		Pager p = page.getPager();
		p.setRowCount(rowCount);
		p.setPageOffset(page.getPage() * page.getRows());
		p.setPageTail(page.getRows() * (page.getPage() - 1));
		return businessDetailMapper.queryByList(page);
	}
}